<template>
  <div class="about-master-container">
    <base-breadcrumb :breadcrumb="!isAudit">
      <a-form-model
        ref="RuleForm"
        :model="formData"
        :rules="rules"
      >
        <a-tabs
          type="card"
          default-active-key="floors"
          class="card-tab"
          @change="getTabChange"
        >
          <a-tab-pane
            key="floors"
            tab="维保信息"
          >
            <div>
              <a-card
                v-loading="loading || projectLoading"
                :bordered="false"
              >
                <title-name title="基本信息" />
                <a-row>
                  <a-col span="8">
                    <a-form-model-item label="维保单编号">
                      <BaseInput
                        v-model="formData.code"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <!-- <a-col span="8">
                    <a-form-model-item label="所属分公司">
                      <SelectSubCompany
                        v-model="formData.branchComId"
                        disabled
                        placeholder="请选择"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item
                      label="项目名称"
                    >
                      <BaseInput
                        v-model="formData.projectName"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col> -->
                  <a-col span="16">
                    <a-form-model-item
                      label="所属单位"
                      prop="projectId"
                    >
                      <OrgTreeSelect
                        v-model="formData.projectId"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="业态">
                      <BaseInput
                        v-model="formData.formats"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item label="合同维保截止时间">
                      <a-date-picker
                        v-model="formData.maintenancePeriodCloseTime"
                        disabled
                        placeholder=""
                        type="date"
                        value-format="YYYY-MM-DD"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item
                      label="质保金总额(万元)"
                      prop="amount"
                    >
                      <BaseInputNumber
                        v-model="formData.amount"
                        placeholder="请输入"
                        :disabled="state == 3"
                      />
                      <!-- <BaseInput
                        v-model="formData.amount"
                        :disabled="state == 3"
                      /> -->
                    </a-form-model-item>
                  </a-col>

                  <a-col span="8">
                    <a-form-model-item label="建设单位">
                      <BaseInput
                        v-model="formData.constructionUnit"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="竣工日期">
                      <BaseInput
                        v-model="formData.completionTime"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="维保年限">
                      <BaseInput
                        v-model="formData.maintenancePeriodYear"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-card>
              <a-card
                v-loading="loading"
                :bordered="false"
              >
                <title-name title="维保信息" />
                <a-row>
                  <a-col span="8">
                    <a-form-model-item label="维保发起人">
                      <BaseInput
                        v-model="formData.createUser"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="联系电话">
                      <BaseInput
                        v-model="formData.phone"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="维保发生周期">
                      <BaseInput
                        v-model="formData.maintenanceCycle"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="维保发起时间">
                      <BaseInput
                        v-model="formData.createTime"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item
                      label="责任分包"
                      prop="subContractorId"
                    >
                      <a-select
                        v-model="formData.subContractorId"
                        placeholder="请选择责任分包"
                        :disabled="state == 3"
                        @change="getsubcontracting"
                      >
                        <a-select-option
                          v-for="item in typeData"
                          :key="item.id"
                          :value="item.id"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item
                      label="维修部位"
                      prop="repairPosition"
                    >
                      <BaseInput
                        v-model="formData.repairPosition"
                        :disabled="state == 3"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item
                      label="维保事项"
                      prop="infoId"
                    >
                      <BaseInput
                        v-model="formData.infoName"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="16">
                    <a-form-model-item
                      label="维保诉求"
                      prop="content"
                    >
                      <BaseTextarea
                        v-model="formData.reason"
                        :max-length="10000"
                        disabled
                        placeholder="请输入"
                      />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-card>
            </div>
          </a-tab-pane>
          <a-tab-pane
            v-if="formData.plan"
            key="floors-two"
            tab="维保方案信息"
          >
            <div>
              <a-card
                v-loading="loading"
                :bordered="false"
              >
                <title-name title="维保方案信息" />
                <a-row>
                  <a-col span="8">
                    <a-form-model-item label="维保方案编号">
                      <BaseInput
                        v-model="formData.plan.maintenancePlanCode"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="维保方案状态">
                      <BaseInput
                        v-model="formData.plan.maintenancePlanStatus"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="预计维保金额(万元)">
                      <BaseInput
                        v-model="formData.plan.maintenanceFee"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="实施分包单位">
                      <BaseInput
                        v-model="formData.plan.implementSubOrg"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="负责人">
                      <BaseInput
                        v-model="formData.plan.responsible"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="8">
                    <a-form-model-item label="维修计划完成时间">
                      <BaseInput
                        v-model="formData.plan.planCompletedTime"
                        disabled
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col span="24">
                    <a-form-model-item label="实施维修内容">
                      <BaseTextarea
                        v-model="formData.plan.implementContent"
                        :max-length="10000"
                        disabled
                        placeholder="请输入"
                      />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-card>
              <a-card
                v-loading="loading"
                :bordered="false"
              >
                <title-name title="相关附件" />

                <UploadTableNew
                  ref="uploadTable"
                  disabled="true"
                  :mode="file.mode"
                  :init-file-list="formData.plan.fileList"
                  :need-page="false"
                  :business-code="'CUSTOMER04'"
                  :use-multi-delete="true"
                  :use-multi-export="true"
                />
              </a-card>
            </div>
          </a-tab-pane>
          <a-tab-pane
            v-for="(item,index) in formData.handleData"
            :key="'floors-res' + index"
            :tab="'处理信息' + '(' + (index + 1) + ')'"
          >
            <a-card
              v-loading="loading"
              :bordered="false"
            >
              <title-name title="处理信息" />
              <a-row>
                <a-col span="8">
                  <a-form-model-item label="处理人">
                    <BaseInput
                      v-model="item.handler"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="处理时间">
                    <BaseInput
                      v-model="item.handleTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="维保事项花费(万元)"
                    :prop="'handleData.'+index+'.cost'"
                    :rules="{ required: true, message: '请输入维保事项花费', trigger: 'blur'}"
                  >
                    <BaseInputNumber
                      v-model="item.cost"
                      placeholder="请输入"
                      :max-length="1000"
                      :disabled="state == 3|| (state == 2 && index < formData.handleTimes)"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item
                    label="处理结果"
                    :prop="'handleData.'+index+'.handleResult'"
                    :rules="{ required: true, message: '请输入处理结果', trigger: 'blur'}"
                  >
                    <BaseTextarea
                      v-model="item.handleResult"
                      :max-length="10000"
                      :disabled="state == 3|| (state == 2 && index < formData.handleTimes)"
                      placeholder="请输入"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-card>
            <a-card
              v-loading="loading"
              :bordered="false"
            >
              <title-name title="相关附件" />

              <UploadTableNew
                ref="uploadTable"
                :disabled="state == 3|| (state == 2 && index < formData.handleTimes)"
                :mode="file.mode"
                :init-file-list="item.fileList"
                :need-page="false"
                :business-code="'CUSTOMER01'"
                :use-multi-delete="true"
                :use-multi-export="true"
              />
            </a-card>
          </a-tab-pane>
        </a-tabs>
      </a-form-model>

      <div v-if="!isConsultation" class="pub-header-btn page-btn-right-top">
        <a-button
          v-if="state == 2"
          :loading="loading"
          type="primary"
          @click="onSave"
        >
          保存
        </a-button>
        <a-button
          v-if="state == 2"
          :loading="loading"
          type="primary"
          @click="submit"
        >
          提交
        </a-button>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
    </base-breadcrumb>
    <selectApprover
      :businessId="businessId"
      :processConfig="setProcessConfig"
    ></selectApprover>
  </div>
</template>

<script>
import { getLoginsList } from '@/api/project/loginInfo'
import { selectOption } from '@/api/material/goods/goods'
import { planAddFile, planFileList, planFileListDel } from '@/api/material/procurement/plan'
import {
  getSubContractorList,
  submitManager,
  addCustomerComplaint,
  getProjectInfo,
  getPCProjectList,
  getOwnerInfoList,
  updateByPrimaryKeySelective,
  getComplaintTree,
  getCustomerComplaintById
} from '@/api/complaint/maintenance'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司

export default {
  name: 'a' + Date.now(),
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      levelData: [
        {
          name: '一般投诉',
          id: '1'
        },
        {
          name: '严重投诉',
          id: '2'
        },
        {
          name: '紧急投诉',
          id: '3'
        }
      ],
      key: '1',
      loading: false,
      state: Number(this.$route.query.state),
      isSubmit: false,
      statuCode: '3',
      row: this.$route.query.row,
      form: { editorName: '', subContractUnitId: '' },
      formData: {},
      rules: {
        maintenancePeriodCloseTime: { required: true, message: '请选择合同维保截止时间', trigger: 'change' },
        projectId: { required: true, message: '请选择项目名称', trigger: 'change' },
        subContractorId: { required: true, message: '请选择责任分包', trigger: 'change' },
        responsible: { required: true, message: '请选择投诉责任方', trigger: 'change' },
        repairPosition: { required: true, message: '请输入维修部位', trigger: 'blur' },
        infoId: { required: true, message: '请选择维修事项', trigger: 'change' },
        complainant: { required: true, message: '请选择投诉人', trigger: 'change' },
        amount: { required: true, message: '请输入质保总金额', trigger: 'blur' },
        maintenancePeriodYear: { required: true, message: '请输入维保年限', trigger: 'blur' },
        cost: { required: true, message: '请输入维保事项花费(万元)', trigger: 'blur' },
        handleResult: { required: true, message: '请输入处理结果', trigger: 'blur' }
      },
      file: {
        mode: this.$route.query.pageTyp === 'add' ? 'add' : 'edit',
        businessCode: 'CUSTOMER01',
        needPage: false,
        fileList: [],
        useMultiDelete: true,
        useMultiExport: true
      },
      projectLoading: false,
      tsUserOptions: [],
      planAddFile: planAddFile(),
      planFileList: planFileList(),
      planFileListDel: planFileListDel(),
      getProgrammeArr: [],
      bimData: [],
      proData: [],
      subcontractingData: [],
      treeLoading: false,
      yhData: [],
      typeData: [],
      projectData: [],
      ownerData: [],
      handlist: [],
      treeData: [],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  components: {
    SelectSubCompany
  },

  watch: {
    formData: {
      deep: true,
      handler() {
        this.$checkRequireItem()
      }
    },
    isAudit: {
      // 是否作为审批详情
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    }
  },
  async created() {
    this.initCode()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('maintenance_01')
  },
  mounted: function () {
    if (this.state != 1) {
      this.getDetail()
      this.isSubmit = true
    }
  },
  methods: {
    getsubcontracting(e) {
      const data = this.typeData.find((item) => item.id == e)
      if (data.name) {
        this.formData = { ...this.formData, subContractorName: data.name }
      }
    },
    getTabChange(e) {
      this.$checkRequireItem()
    },
    getLevel(e) {
      const levelData = this.treeData.find((item) => item.id == e)
      this.formData.level = levelData.type
    },
    getPhone(e) {
      this.formData.phone = this.ownerData.find((item) => item.name == e).phone
      this.formData.complainantId = this.ownerData.find((item) => item.name == e).id
    },
    deepClone2(obj) {
      var _obj = JSON.stringify(obj),
        objClone = JSON.parse(_obj)
      return objClone
    },
    getDetail() {
      this.loading = true
      getCustomerComplaintById({ id: this.$route.query.id }).then((res) => {
        this.handlist = this.deepClone2(res.data.handList)
        if (res.data.subContractorId == null) {
          res.data.subContractorId = undefined
        }
        if (res.data.handList.length == 0) {
          res.data.handleData = [
            {
              fileList: []
            }
          ]
        } else {
          if (this.state == 2 && res.data.handList.length === res.data.handleTimes) {
            res.data.handList.push({
              fileList: []
            })
          }
          res.data.handleData = res.data.handList
        }

        res.data.type = Number(res.data.type)
        res.data.infoId = Number(res.data.infoId)
        getSubContractorList({ ProjectId: res.data.projectId }).then((node) => {
          this.typeData = node.data
        })
        getProjectInfo(res.data.projectId).then((resp) => {
          const newData = []
          res.data.handleData.map((item) => {
            newData.push({
              ...item,
              handlerId: resp.data.projectManagerId,
              handler: resp.data.projectManagerName
            })
          })
          res.data.handleData = newData
        })
        this.formData = res.data
        this.loading = false
      })
    },
    getProId(value) {
      this.projectLoading = true
      const data = this.projectData.find((item) => item.id == value)
      getProjectInfo(this.formData.projectId)
        .then((res) => {
          this.projectLoading = false
        })
        .catch((err) => {
          this.projectLoading = false
        })
      getOwnerInfoList(this.formData.projectId).then((res) => {
        this.ownerData = res.data
      })
    },
    getTreeId(e) {
      let type = ''
      this.typeData.map((item) => {
        item.childrenList.map((ite) => {
          if (ite.id == e) {
            type = ite.type
          }
        })
      })
      this.treeLoading = true
      this.formData = { ...this.formData, level: '', infoId: '', type: type, treeId: e }
      getComplaintTree({ treeId: e })
        .then((res) => {
          this.treeData = res.data
          this.treeLoading = false
        })
        .catch((err) => {
          this.treeLoading = false
        })
    },
    initCode() {
      this.loading = true
      getPCProjectList().then((res) => {
        this.projectData = res.data
      })
    },
    getProgramme: function () {
      let _this = this
      selectOption({
        type: 18
      }).then((res) => {
        if (res.code === 200) {
          _this.getProgrammeArr = res.data
        }
      })
      getLoginsList({}).then((res) => {
        if (res.code === 200) {
          _this.tsUserOptions = res.data
        }
      })
    },
    //  保存并提交
    onAdd() {
      this.loading = true
      // this.formData.fileList = this.file.fileList
      this.formData.insertType = 1
      addCustomerComplaint(this.formData)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('提交成功')
            this.$multiTab.close(this.$route.fullpath)
            this.loading = false
          }
        })
        .catch((err) => {
          this.loading = false
        })
    },
    // 编辑新增时候的保存
    onSave() {
      this.loading = true
      if (this.formData.handleData.length != 0) {
        this.formData.hand = this.formData.handleData[this.formData.handleData.length - 1]
        const newHandleData = []
        this.formData.handleData.map((item) => {
          newHandleData.push({
            ...item,
            createTime: null,
            handleTime: null
          })
        })
        this.formData = { ...this.formData, hand: { ...this.formData.hand, handleTime: null, createTime: null }, handleData: newHandleData }
      } else {
        this.formData.handleData = {}
      }
      this.formData.handList = null
      this.formData.createTime = null
      this.formData.updateTime = null
      updateByPrimaryKeySelective(this.formData)
        .then((res) => {
          if (res.code == 200) {
            this.loading = false
            this.$message.success('保存成功')
            this.$multiTab.close(this.$route.fullpath)
          }
        })
        .catch((err) => {
          this.loading = false
        })
    },
    submit() {
      this.setProcessConfig = null
      this.$refs.RuleForm.validate((valid) => {
        if (valid) {
        this.submitApprovalConfirm(this.processConfig, (flag)=>{
            if(!flag) {
              this.loading = false
              return
            }
            this.loading = true
            if (this.formData.handleData.length != 0) {
              this.formData.hand = this.formData.handleData[this.formData.handleData.length - 1]
              const newHandleData = []
              this.formData.handleData.map((item) => {
                newHandleData.push({
                  ...item,
                  handleTime: null,
                  createTime: null
                })
              })
              this.formData = { ...this.formData, hand: { ...this.formData.hand, handleTime: null, createTime: null }, handleData: newHandleData }
            } else {
              this.formData.handleData = null
            }
            this.formData.createTime = null
            this.formData.updateTime = null
            submitManager(this.formData).then((res) => {
              if (res.data?.code == 200 || res.code == 200) {
                this.$message.success('提交成功')
                //提交时，返回id
                this.businessId = res.data?.id || this.formData.id
                this.setProcessConfig = this.processConfig
                this.loading = false
              }
            })
          })
          // })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
